<?php

namespace addons\venue\controller;

use app\admin\model\venue\area\Rule;
use app\admin\model\venue\venue\Relationship;
use app\admin\model\venue\venue\Reserve;
use app\admin\model\venue\venue\Type;
use app\admin\model\venue\venue\Venue as Vu;
use app\common\controller\Api;
use think\Request;

class Venue extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getPrices','getType','getVenue','getVenues','getVenueDetail','getArea','getVenueType','times','getRmVenue'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $config = "";

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("venue");
        parent::__construct($request);
    }

    /*
     * 筛选的价格区间
     */
    public function getPrices(){
        $data = [
            [
                "min_price"=>"0",
                "max_price"=>"50"
            ],
            [
                "min_price"=>"50",
                "max_price"=>"100"
            ],
            [
                "min_price"=>"100",
                "max_price"=>"200"
            ],
        ];
        $this->success('返回成功',$data);
    }

    /*
     * 获取场馆分类
     */
    public function getType(){

        $data = Type::where('state',1)
                ->order('weigh', 'desc')
                ->field("id,venue_type,image,imaged")
                ->select()
                ->each(function ($item){
                    $item->image = cdnurl($item->image,true);
                    $item->imaged = cdnurl($item->imaged,true);
                });

        $this->success('返回成功',$data);

    }

    /*
     * 获取场馆列表
     */
    public function getVenue(){
        $lon = $this->request->header("lon")??'113.663221';
        $lat = $this->request->header("lat")??'34.7568711';
        $order   = $this->request->post('order')??1;//排序方式 1：综合排序 2：价格最低 3：价格最高 4：距离最近
        $type   = $this->request->post('type');
        $page   = $this->request->post('page')??1;  //页码
        $limit  = $this->request->post('limit')??10; //每页显示条数
//        $switch  = $this->request->post('switch')??1; //营业开关 默认1
        $min_price  = $this->request->post('min_price'); //最低价格
        $max_price  = $this->request->post('max_price'); //最高价格
        $search  = $this->request->post('search')??""; //搜索条件
        $where = [];
        if ($type){
            $where["venue_type_id"] = ['like',"%".$type."%"];
        }
        if ($order == 1){
            $order = "weigh desc";
        }elseif ($order == 2){
            $order = "lower_price asc";
        }elseif ($order == 3){
            $order = "max_price desc";
        }else{
            $order = "distance asc";
        }
//        $where['switch'] = $switch;

        if ($search){
            $where['name'] = ['like',"%".$search."%"];
        }

        //如果传入最低价格和最高价格，则进行价格筛选 要求数据表中的最低价格和最高价格 都必须在传入的最低价格和最高价格之间
        if ($min_price && $max_price){
            $where["max_price"] = ["between",[$min_price,$max_price]];
        }
        
        $data = Vu::where('state',1)
                ->where($where)
                ->order($order)
                ->field("id,name,address,lon,venue_type_id,lat,image,max_price,lower_price,".venue_getDistanceBuilder($lat, $lon))
                ->paginate(["page"=>$page,"list_rows"=>$limit])
                
                ->each(function($item, $key)use($lon,$lat){
                    $item->image = cdnurl($item->image,true);

                    $ids = explode(",",$item->venue_type_id);
                    $arr = [];
                    foreach ($ids as $k=>$v){
                        $type = Type::get($v);
                        $arr[$k]['image']= cdnurl($type['image'],true);
                        $arr[$k]['icon']= cdnurl($type['imagel'],true);
                        $arr[$k]['name']= $type['venue_type'];
                    }
                    $item->type = $arr;
                });
 
                
        $result = array("total" => $data->total(), "rows" => $data->items());
        $this->success('返回成功',$result);
    }

    /*
     * 获取首页热门场馆列表
     */
    public function getRmVenue(){
        $lon = $this->request->header("lon")??'113.663221';
        $lat = $this->request->header("lat")??'34.7568711';

        $data = Vu::where('state',1)
            ->whereLike('flag',"%hot%")
            ->field("id,name,address,lon,venue_type_id,lat,image,max_price,lower_price,".venue_getDistanceBuilder($lat, $lon))
            ->limit(6)
            ->select()
            ->each(function($item, $key)use($lon,$lat){
                $item->image = cdnurl($item->image,true);
                $ids = explode(",",$item->venue_type_id);
                $arr = [];
                foreach ($ids as $k=>$v){
                    $type = Type::get($v);
                    $arr[$k]['image']= cdnurl($type['image'],true);
                    $arr[$k]['icon']= cdnurl($type['imagel'],true);
                    $arr[$k]['name']= $type['venue_type'];
                }
                $item->type = $arr;
            });

        $this->success('返回成功',$data);
    }

    /*
     * 获取场馆详情
     */
    public function getVenueDetail(){
        $lon = $this->request->header("lon")??'113.663221';
        $lat = $this->request->header("lat")??'34.7568711';
        $id   = $this->request->post('id');
        if (!$id){
            $this->error("缺少场馆id");
        }
        $data = Vu::where('state',1)
                ->where('id',$id)
                ->field("id,name,address,lon,lat,image,images,multiplejson,content,tel,image_plan,max_price,lower_price,".venue_getDistanceBuilder($lat, $lon))
                ->find();
        
        $data['content'] = nl2br($data['content']);
        $data['image'] = cdnurl($data['image'],true);
        $data['image_plan'] = cdnurl($data['image_plan'],true);
        if ($data['images']) {
            $images = explode(",", $data['images']);
            foreach ($images as $k => &$v){
                $v = cdnurl($v, true);
            }
            $data['images'] = $images;
        }
        $this->success('返回成功',$data);
    }

    /*
     * 获取场馆类型
     */
    public function getVenueType(){
        $id   = $this->request->post('id');
        if (!$id){
            $this->error("缺少场馆id");
        }
        $data = Vu::where('state',1)
            ->where('id',$id)
            ->field("venue_type_id")
            ->find();
        $data = Type::where("id","in",$data['venue_type_id'])->select()
                ->each(function ($item){
                    $item->icon = cdnurl($item->icon,true);
                    $item->image = cdnurl($item->image,true);
                    $item->imaged = cdnurl($item->imaged,true);
                    $item->imagel = cdnurl($item->imagel,true);
                });
        $this->success('返回成功',$data);
    }



    /*
     * 获取场地信息
     */
    public function getArea(){
        $typeId     = $this->request->post('typeId');  //类型id
        $venueId    = $this->request->post('venueId'); //场馆id
        $time       = $this->request->post('time');    //时间
        if (!$time){
            $time = date("Y-m-d");
        }
        if (!$typeId || !$venueId){
            $this->error("参数不能为空");
        }

        //获取该类型下的场馆场地信息
        $data = Vu::where(["state"=>1])
                ->where("id",$venueId)
                ->order("weigh","desc")
                ->field("id,name,lon,lat,image,address")
                ->select()
                ->each(function($items) use($time,$venueId,$typeId){
                    $items->image = cdnurl($items->image,true);
                    //只返回指定的场馆下面的场地信息
                    if ($items->id == $venueId){
                        //返回数据格式为日期-场地-时间段
                        $area = Relationship::where("venue_id",$venueId)
                                    ->where("type_id",$typeId)
                                    ->field("id,name,rule_id,area_rest")
                                    ->select()
                                    ->each(function($item) use($time,$items){
                                        $rule = Rule::where(['state'=>1,'id'=>$item->rule_id])
                                                ->field("start_times,end_times,interval_time,price,max_number")
                                                ->select();
                                        //场地休息时间
                                        if ($item->area_rest != ""){
                                            $rest_start = explode(" - ",$item->area_rest);
                                        }else{
                                            $rest_start[0] = 0;
                                            $rest_start[1] = 0;
                                        }
                                        //构建时间段数组
                                        $out = [];
                                        $times = [];
                                        foreach ($rule as $v){
                                            $timeFrom = strtotime( $time. $v->start_times);
                                            $step = 60 * (60 * $v->interval_time);//间隔时间
                                            $timeTo = strtotime($time . $v->end_times)-$step;
                                            foreach (range($timeFrom, $timeTo, $step) as $timestamp) {
                                                $arr["time"] = date('H:i', $timestamp);
                                                $arr["end_time"] = date('H:i', bcadd($timestamp,$step));
                                                $times[] = date('H:i', $timestamp);
                                                $arr["price"] = $v->price;
                                                $arr['status'] = 1; //默认状态是1（可预定）
                                                //查询是否已过当前时间
                                                if (time()>$timestamp){
                                                    $arr['status'] = 3;
                                                }
                                                //查询是否处于休息时间 或 已被预定 该时间段处于任何一种 将状态更新为2（不可选）
                                                if (strtotime($rest_start[0])<=$timestamp && strtotime($rest_start[1])>=$timestamp){
                                                    $arr['status'] = 3;
                                                }
                                                
                                                /*
                                                $reserveInfo = Reserve::where(["area_id"=>$item->id,"fixed_date"=>$time,"start_times"=>$arr['time']])
                                                                ->where("order_status",0)
                                                                ->field("fixed_date,start_times,end_times")
                                                                ->select();
//                                                if ($arr['time'] == "18:00"){
//                                                    if (!empty($reserveInfo->toArray())){
//                                                        var_dump(1);
//                                                    }else{
//                                                        var_dump(2);
//                                                    }
//                                                }
                                                if (!empty($reserveInfo->toArray())){
//                                                    var_dump($arr);
                                                    $arr['status'] = 2;
                                                }
                                                */
                                                
                                                //报名人数超过 最大人数,则无法再报名
                                                if(empty($v['max_number'])){
                                                    $v['max_number'] = 999;
                                                }
                                                
                                                $reserve_count = Reserve::where(["area_id"=>$item->id,"fixed_date"=>$time,"start_times"=>$arr['time']])
                                                                ->where("order_status",0)
                                                                ->count();
                                                if($reserve_count >= $v['max_number']){
                                                    $arr['status'] = 2;
                                                }
                                                $arr['max_number']  = $v['max_number'];
                                                $arr['last_number'] = $v['max_number'] - $reserve_count;
                                                
                                                
//                                                if (!empty($reserveInfo->toArray())){
//                                                    //判断该时间段是否已被预定
//                                                    foreach ($reserveInfo as $val){
//                                                        if (strtotime($time." ".$val['start_times'])<=$timestamp && strtotime($time." ".$val['end_times'])>=$timestamp){
//                                                            $arr['status'] = 2;
//                                                        }
//                                                    }
//                                                }
                                                $items->times = $times;
                                                if ($arr['status'] == 1){
                                                    $arr['style'] = "";
                                                }
                                                $out[] = $arr;
 
                                            }
                                        }
                                        //将数据分为上午，下午，晚上三个数组 规则是 上午00:00-12:00 下午13:00-18:00 晚上18:00-24:00
                                        $morning = $middle = $evening = [];
                                        foreach ($out as $k=>$v){
                                            if (substr($v['time'],0,2)<13){
                                                array_push($morning,$v);
                                            }elseif (substr($v['time'],0,2)>12 && substr($v['time'],0,2)<18){
                                                array_push($middle,$v);
                                            }else{
                                                array_push($evening,$v);
                                            }
                                        }

                                        //统计$morning['data']中某个字段等于1的个数
                                        foreach ($morning as $k=>$v){
                                            if ($v == 1){
                                                $morning['count']++;
                                            }
                                        }
                                        //统计$middle['data']中某个字段等于1的个数
                                        foreach ($middle as $k=>$v){
                                            if ($v == 1){
                                                $middle['count']++;
                                            }
                                        }
                                        //统计$evening['data']中某个字段等于1的个数
                                        foreach ($evening as $k=>$v){
                                            if ($v == 1){
                                                $evening['count']++;
                                            }
                                        }
                                        $item->rule_morning = $morning;
                                        $item->rule_middle = $middle;
                                        $item->rule_evening = $evening;
//                                        $item->rule =$out;

                                    });
                        //获取上午，下午，晚上所有可预订状态场次的数量
                        $morning = $middle = $evening = 0;
                        foreach ($area as $k=>$v){
                            foreach ($v->rule_morning as $value) {
                                if ($value['status'] == 1) {
                                    $morning++;
                                }
                            }
                            foreach ($v->rule_middle as $value) {
                                if ($value['status'] == 1) {
                                    $middle++;
                                }
                            }
                            foreach ($v->rule_evening as $value) {
                                if ($value['status'] == 1) {
                                    $evening++;
                                }
                            }
                        }
                        $items->morning_count = $morning;
                        $items->middle_count = $middle;
                        $items->evening_count = $evening;
                        $items->day = $area;
                    }
                });
        $this->success('返回成功',$data);
    }

    /*
     * 获取时间
     */
    public function times(){
        $arr = [];
        $weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
        for ($i=0;$i<5;$i++){
            $date = date("Y-m-d",strtotime("+$i day"));
            $arr[$i]['date'] = $date;
            $arr[$i]['date_jl'] = substr($date,strripos($date,"-")+1);
            $arr[$i]['xq'] = "星期".$weekarray[date("w",strtotime($date))];

        }
        $this->success("成功",$arr);
    }

}
